package com.neo.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.neo.entity.Awardstable;
import com.neo.entity.User;
import com.neo.mapper.IAwardstableDAO;
import com.neo.mapper.IUserDAO;
import com.neo.service.ILotteryService;
import com.neo.vo.ResultVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Author: xihao.ding
 * @CreateDate: 2018/12/8 16:42
 */
@Service
public class LotteryServiceImpl implements ILotteryService{

    private final static Logger logger = LoggerFactory.getLogger(LotteryServiceImpl.class);

    @Autowired
    private IUserDAO iUserDAO;

    @Autowired
    private IAwardstableDAO iAwardstableDAO;

    @Override
    public Map<String, Object> pre() {
        Map<String,Object> map = new HashMap<>();
        Map<String,Object> condition = new HashMap<>();
        List<Awardstable> awardstableList = iAwardstableDAO.findByCondition(condition);
        if(awardstableList != null && !awardstableList.isEmpty()){
            List<Awardstable> first = awardstableList.stream().filter(e -> e.getAwards().equals("一等奖")).collect(Collectors.toList());
            List<Awardstable> second = awardstableList.stream().filter(e -> e.getAwards().equals("二等奖")).collect(Collectors.toList());
            List<Awardstable> third = awardstableList.stream().filter(e -> e.getAwards().equals("三等奖")).collect(Collectors.toList());
            map.put("first",first);
            map.put("second",second);
            map.put("third",third);
        }
        return map;
    }

    @Override
    public ResultVO<Map> lotteryData() {
        ResultVO<Map> resultVO = new ResultVO<>();
        try {
            Map<String,Object> map;
            map = this.pre();
            resultVO.setCode(0);
            resultVO.setData(map);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("查询名单失败" , e);
        }
        return resultVO;
    }

    @Override
    @Transactional
    public JSONObject begin(String awards ,Integer personCount) {
        JSONObject resultJson = new JSONObject();
        try{
            logger.info("奖项-----------：{},中奖人数----：{}" , awards , personCount);

            // 查询所有用户
            List<User> userList = iUserDAO.findByCondition(new HashMap<>());

            // 查询已经抽过的用户
            Map<String , Object> condition = new HashMap<>();
            List<Awardstable> awardstableList = iAwardstableDAO.findByCondition(condition);

            if(awardstableList != null && awardstableList.size() > 0){
                // 已经有抽过该奖项的人,这些人要屏蔽掉,userList里放的就是没抽过的人
                userList = this.filter(userList ,awardstableList);
            }
            // 如果人数已经不够你抽奖的次数 就返回
            if(userList.size() < personCount){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("result","error");
                jsonObject.put("msg","预留人数小于抽奖人数了");
                return jsonObject;
            }
            // key 是id value 是user
            Map<Integer , User> map = new HashMap<>();
            userList.forEach(
                    user -> {
                        map.put(user.getId() , user);
                    }
            );
            // 存放用户id的集合
            List<Integer> userIds = userList.stream().map(e -> e.getId()).collect(Collectors.toList());

            // 中奖的集合 里面放到额是id
            List<Integer> result = new ArrayList<>();

            // 初始化随机数
            Random rand = new Random();

            // 循环抽奖次数
            for (int i = 0; i < personCount; i++) {
                // 任意取一个0~size的整数，注意此处的items.size()是变化的，所以不能用前面的size会发生数组越界的异常
                int myRand = rand.nextInt(userIds.size());
                // 将取出的这个元素放到存放中将的集合中
                result.add(userIds.get(myRand));
                // 从原始集合中删除该元素防止重复。注意，items数组大小发生了改变
                userIds.remove(myRand);
            }

            // 接下就把result 里对应的去map 里找出user 并存入 对应 记录表，
            JSONArray jsonArray = new JSONArray();
            for(Integer userId : result){
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userName" ,  map.get(userId).getName());
                jsonObject.put("awards" ,  awards);
                jsonObject.put("userId" ,  map.get(userId).getId());
                jsonArray.add(jsonObject);
            }
            resultJson.put("result","success");
            resultJson.put("data",jsonArray);
        }catch (Exception e){
            logger.error("抽奖异常：{}",e);
            resultJson.put("result","error");
            resultJson.put("msg","抽奖异常");
        }
        return resultJson;

    }

    @Override
    @Transactional
    public JSONObject save(String data) {
        JSONObject resultJson = new JSONObject();
        try{
            if(StringUtils.isNotBlank(data)){
                JSONArray jsonArray = JSONArray.parseArray(data);
                Iterator<Object> iterator = jsonArray.iterator();
                while(iterator.hasNext()){
                    JSONObject jsonObject = (JSONObject)iterator.next();
                    Awardstable awardstable = new Awardstable();
                    awardstable.setUserId(jsonObject.getInteger("userId"));
                    awardstable.setAwards(jsonObject.getString("awards"));
                    awardstable.setUserName(jsonObject.getString("userName"));
                    iAwardstableDAO.insert(awardstable);
                }
            }
            resultJson.put("result","success");
        }catch (Exception e){
            logger.error("保存失败：{}" , e);
            resultJson.put("result","error");
            resultJson.put("msg","保存失败");
        }
        return resultJson;
    }

    public List<User> filter(List<User> userList , List<Awardstable> awardstableList){
        if(userList == null && userList.isEmpty()){
            return null;
        }
        List<Integer> collect = awardstableList.stream().map(e -> e.getUserId()).collect(Collectors.toList());
        logger.info("已经抽过的id---------:{}",collect);
        List<Integer> totalId = userList.stream().map(e -> e.getId()).collect(Collectors.toList());
        logger.info("全部的用户id---------:{}",totalId);

        // userList和awardstableList想比较，如果存在awardstableList中flag 为true
        List<User> newUserList = new ArrayList<>();
        for(User user : userList){
            boolean flag = false;
            for(Awardstable awardstable : awardstableList){
                if(user.getId().intValue() == awardstable.getUserId().intValue()){
                    flag = true;
                }
            }
            if(!flag){
                newUserList.add(user);
            }
        }
        return newUserList;
    }
}
